<?php

/**
 * Created by PhpStorm.
 * User: 董兴涛
 * Date: 2020/7/18
 * Time: 16:49
 */

namespace app\engine\controller;

use cmf\controller\HomeBaseController;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class TeamController extends HomeBaseController
{

    /**
     * 加载首页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function manager()
    {
        $id = $this->request->param();
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 加载首页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function index()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $res = Db::name('final')->where(['eid' => $id])->group('type')->field('type')->select()->toArray();
        $this->assign('data', $res);
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 添加项目页
     * @return mixed|string
     */
    public function add()
    {
        $data = $this->request->param();
        $type = $data['type'];
        if ($type == 1) {
            $some = Db::name('leader')->where(['eid' => $data['id']])->field('id,type,name')->select()->toArray();
        } else {
            $some = Db::name('supplier')->where(['able' => 1])->field('id,attrName,name')->select()->toArray();
        }

        $this->assign('id', $data['id']);
        $this->assign('some', $some);
        $this->assign('type', $type);
        if ($type == 1) {
            return $this->fetch();
        } elseif ($type == 2) {
            return $this->fetch('adds');
        } else {
            return $this->fetch('addes');
        }
    }

    /**
     * 添加项目
     */
    public function doadd()
    {
        $data = $this->request->param();
        $kps = [];
        $pop = [];
        $zop = [];

        if ($data['type'] == 1) {
            $check = Db::name('final')->where('eid', $data['eid'])->where(['lid' => $data['lid'], 'type' => 1])->find();
            if ($check) {
                $this->error('该班组姓名已存在');
            }
            $files = $this->request->file('img');
            $ht = $this->request->file('contract');
            if ($files) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
                $data['img'] = implode(',', $kps);
            }
            if ($ht) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($ht as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $pop[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
                $data['contract'] = implode(',', $pop);
            }
        } elseif ($data['type'] == 2) {
            $check = Db::name('final')->where('eid', $data['eid'])->where(['tid' => $data['tid'], 'type' => 2])->find();
            if ($check) {
                $this->error('该供应商已存在');
            }
            $files = $this->request->file('img');
            $ht = $this->request->file('contract');
            if ($files) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
                $data['img'] = implode(',', $kps);
            }
            if ($ht) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($ht as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $pop[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
                $data['contract'] = implode(',', $pop);
            }
        } elseif ($data['type'] == 3) {
            $check = Db::name('final')->where('eid', $data['eid'])->where(['lid' => $data['lid'], 'type' => 3])->find();
            if ($check) {
                $this->error('该供应商已存在');
            }
        }
        $res = Db::name('final')->insert($data);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    /**
     * 项目详情
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function see()
    {
        $data = $this->request->param();
        if (empty($data['id'])) {
            $this->error('缺少参数');
        }
        $res = Db::name('final')->where(['id' => $data['id']])->find();
        if ($res['type'] == 1) {
            if (!empty($res['img'])) {
                $res['img'] = explode(',', $res['img']);
                foreach ($res['img'] as $k => &$v) {
                    $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
                }
            }

            if (!empty($res['contract'])) {
                $res['contract'] = explode(',', $res['contract']);

                foreach ($res['contract'] as $k => &$p) {
                    $p = 'http://' . $_SERVER['SERVER_NAME'] . $p;
                }
            }
        } elseif ($res['type'] == 2) {
            if (!empty($res['img'])) {
                $res['img'] = explode(',', $res['img']);
                foreach ($res['img'] as $k => &$v) {
                    $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
                }
            }

            if (!empty($res['contract'])) {
                $res['contract'] = explode(',', $res['contract']);
                foreach ($res['contract'] as $k => &$p) {
                    $p = 'http://' . $_SERVER['SERVER_NAME'] . $p;
                }
            }
        }
        // var_dump($res);die;

        if ($res['type'] == 1) {
            $some = Db::name('leader')->field('id,name,type')->select()->toArray();
            $res['lName'] = Db::name('leader')->where(['id' => $res['lid']])->value('name');
            $res['ltype'] = Db::name('leader')->where(['id' => $res['tid']])->value('type');
        } else {
            $some = Db::name('supplier')->where(['able' => 1])->field('id,attrName,name')->select()->toArray();
            $res['lName'] = Db::name('supplier')->where(['id' => $res['lid']])->value('attrName');
            $res['lType'] = Db::name('supplier')->where(['id' => $res['tid']])->value('name');
        }
        $this->assign('some', $some);
        $this->assign('res', $res);
        if ($res['type'] == 1) {
            return $this->fetch();
        } elseif ($res['type'] == 2) {
            return $this->fetch('sees');
        } elseif ($res['type'] == 3) {
            return $this->fetch('seees');
        }
    }

    /**
     * 删除项目页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function del()
    {
        $data = $this->request->param();
        $check = Db::name('final')->where(['id' => $data['id']])->value('img');
        $img = CMF_ROOT . $check;
        if ($img != CMF_ROOT) {
            if (file_exists($img)) {
                unlink($img);
            }
        }
        $res = Db::name('final')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 项目编辑页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function edit()
    {
        $data = $this->request->param();
        if (cmf_get_current_admin_id() != 1) {
            $this->error('无权限操作');
        }
        $res = Db::name('final')->where('id', $data['id'])->find();
        $this->assign('res', $res);
        return $this->fetch();
    }

    /**
     * 项目编辑
     * @throws Exception
     * @throws PDOException
     */
    public function doedit()
    {
        $data = $this->request->param();
        $files = request()->file('img');
        $contract = request()->file('contract');
        $id = $data['id'];
        unset($data['id']);
        $check = Db::name('final')->where(['id' => $id])->find();

        // 处理要删除的图片
        $removeImg = isset($data['remove_img']) ? $data['remove_img'] : [];
        $removeContract = isset($data['remove_contract']) ? $data['remove_contract'] : [];
        unset($data['remove_img']);
        unset($data['remove_contract']);

        // 处理保留的旧图片
        $oldImg = isset($data['old_img']) ? $data['old_img'] : [];
        $oldContract = isset($data['old_contract']) ? $data['old_contract'] : [];
        unset($data['old_img']);
        unset($data['old_contract']);

        // 处理决算明细图片
        if (!is_null($files) || !empty($removeImg)) {
            $kps = [];
            // 如果有旧图片，先添加到数组中
            if (!empty($oldImg)) {
                // 处理旧图片，去除域名只保留路径
                foreach ($oldImg as $img) {
                    if (!empty($img)) {
                        // 如果图片路径包含域名，只保留路径部分
                        if (strpos($img, 'http://') === 0 || strpos($img, 'https://') === 0) {
                            $parsedUrl = parse_url($img);
                            $kps[] = $parsedUrl['path'];
                        } else {
                            $kps[] = $img;
                        }
                    }
                }
            } else if (!empty($check['img']) && empty($removeImg)) {
                // 如果没有指定旧图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
                $imgArray = explode(',', $check['img']);
                foreach ($imgArray as $img) {
                    if (!empty($img)) {
                        $kps[] = $img;
                    }
                }
            }

            // 处理新上传的图片
            if (!is_null($files)) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
            }

            $data['img'] = implode(',', $kps);
        }

        // 处理合同图片
        if (!is_null($contract) || !empty($removeContract)) {
            $pop = [];

            // 如果有旧合同图片，先添加到数组中
            if (!empty($oldContract)) {
                // 处理旧合同图片，去除域名只保留路径
                foreach ($oldContract as $cont) {
                    if (!empty($cont)) {
                        // 如果合同路径包含域名，只保留路径部分
                        if (strpos($cont, 'http://') === 0 || strpos($cont, 'https://') === 0) {
                            $parsedUrl = parse_url($cont);
                            $pop[] = $parsedUrl['path'];
                        } else {
                            $pop[] = $cont;
                        }
                    }
                }
            } else if (!empty($check['contract']) && empty($removeContract)) {
                // 如果没有指定旧合同图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
                $contractArray = explode(',', $check['contract']);
                foreach ($contractArray as $cont) {
                    if (!empty($cont)) {
                        $pop[] = $cont;
                    }
                }
            }

            // 处理新上传的合同图片
            if (!is_null($contract)) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($contract as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $pop[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
            }

            $data['contract'] = implode(',', $pop);
        }

        $data['createTime'] = date('Y-m-d H:i:s');
        $res = Db::name('final')->where('id', $id)->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 搜索
     */
    public function search()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $where = ['eid' => $id];
        if (isset($data['type']) && !empty($data['type'])) {
            $where['type'] = $data['type'];
        }
        $res = Db::name('final')->where($where)->select()->toArray();
        foreach ($res as $k => &$v) {
            if ($v['type'] == 1) {
                $v['lname'] = Db::name('leader')->where(['id' => $v['lid']])->value('name');
            } else {
                $v['lname'] = Db::name('supplier')->where(['id' => $v['lid']])->value('attrName');
            }
        }
        $this->assign('id', $id);
        $this->assign('data', $res);
        return $this->fetch();
    }

    public function sees()
    {
        $data = $this->request->param();
        $id = $data['eid'];
        $type = $data['type'];
        $res = Db::name('final')->where(['eid' => $id, 'type' => $type])->select()->toArray();
        foreach ($res as $k => &$v) {
            if ($v['type'] == 1) {
                $v['lname'] = Db::name('leader')->where(['id' => $v['lid']])->value('name');
            } else {
                $v['lname'] = Db::name('supplier')->where(['id' => $v['tid']])->value('attrName');
                $v['Sname'] = Db::name('supplier')->where(['id' => $v['tid']])->value('name');
            }

            if ($v['type'] == 1) {
                $v['pay'] = Db::name('life')->where(['eid' => $id, 'lid' => $v['lid'], 'type' => 1])->sum('price');
                if (intval($v['deciPrice']) == 0) {
                    $v['bance'] = ($v['tempPrice'] + $v['deciPrice']) - $v['deciPrice'] - $v['pay'];
                } else {
                    $v['bance'] = ($v['tempPrice'] + $v['deciPrice']) - $v['tempPrice'] - $v['pay'];
                }
            } elseif ($v['type'] == 2) {
                $v['pay'] = Db::name('life')->where(['eid' => $id, 'lid' => $v['lid'], 'type' => 2])->sum('price');
                if (intval($v['deciPrice']) == 0) {
                    $v['bance'] = ($v['tempPrice'] + $v['deciPrice']) - $v['deciPrice'] - $v['pay'];
                } else {
                    $v['bance'] = ($v['tempPrice'] + $v['deciPrice']) - $v['tempPrice'] - $v['pay'];
                }
            } elseif ($v['type'] == 3) {
                $v['deciPrice'] = Db::name('run_bill')->where(['eid' => $id, 'supplier' => $v['tid']])->sum('count');
                $v['pay'] = Db::name('life')->where(['eid' => $id, 'lid' => $v['tid'], 'type' => 2])->sum('price');
                $v['bance'] = $v['deciPrice'] - $v['pay'];
            }
        }
        $this->assign('data', $res);
        $this->assign('id', $id);
        if ($type == 1) {
            $all = 0;
            $back = 0;
            $sign = 0;
            foreach ($res as $k => &$v) {
                $all += $v['deciPrice'];
                $back += $v['pay'];
                $sign += $v['bance'];
            }
            $this->assign('all', $all);
            $this->assign('back', $back);
            $this->assign('sign', $sign);
            return $this->fetch('indexs');
        } elseif ($type == 2) {
            return $this->fetch('indexes');
        } else {
            return $this->fetch('indexess');
        }
    }
}